import 'package:flutter/material.dart';

class HorizontalDashedLine extends StatelessWidget {
  final double width;
  final double height;
  final double dashWidth;
  final double dashSpace;
  final Color color;

  const HorizontalDashedLine({
    super.key,
    required this.width,
    this.height = 1,
    this.dashWidth = 5,
    this.dashSpace = 3,
    this.color = Colors.black,
  });

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(width, height),
      painter: DashedLinePainter(
        dashWidth: dashWidth,
        dashSpace: dashSpace,
        color: color,
      ),
    );
  }
}

class DashedLinePainter extends CustomPainter {
  final double dashWidth;
  final double dashSpace;
  final Color color;

  DashedLinePainter({
    required this.dashWidth,
    required this.dashSpace,
    required this.color,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = size.height
      ..style = PaintingStyle.stroke;

    final totalLength = dashWidth + dashSpace;
    final dashCount = (size.width / totalLength).floor();

    for (int i = 0; i < dashCount; i++) {
      final startX = i * totalLength;
      canvas.drawLine(
        Offset(startX, size.height / 2),
        Offset(startX + dashWidth, size.height / 2),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // 先判断 oldDelegate 是否为 DashedLinePainter 类型
    if (oldDelegate is DashedLinePainter) {
      return oldDelegate.dashWidth != dashWidth ||
          oldDelegate.dashSpace != dashSpace ||
          oldDelegate.color != color;
    }
    return true;
  }
}

// void main() {
//   runApp(
//     MaterialApp(
//       home: Scaffold(
//         appBar: AppBar(title: const Text('Horizontal Dashed Line')),
//         body: Center(
//           child: HorizontalDashedLine(
//             width: 200,
//             color: Colors.blue,
//           ),
//         ),
//       ),
//     ),
//   );
// }